package leetcode;

import java.util.Arrays;

/**
 * @author K
 * @date 2024/1/16 13:54
 */
public class SolutionCustom {

    public static void main(String[] args) {
        SolutionCustom solution = new SolutionCustom();
        int i = solution.lessNMax(new int[]{ 1, 2, 9, 4}, 23846);
        int i1 = solution.lessNMax(new int[]{ 1, 2, 9, 4}, 20000);
        int i2 = solution.lessNMax(new int[]{ 1, 2, 9, 4}, 2533);

        System.out.println();
    }

    /**
     * 小于N的最大数
     */
    public Integer lessNMax(int[] nums, int x) {
        String xStr = String.valueOf(x);
        Arrays.sort(nums);
        //是否允许直接查找最大值
        //例如2533 找到第二个数5时，给定的数里面只有4最大，那么24小于25，找第三、四个数时就可以直接找最大数9，最后就是2499
        boolean allowMax = false;
        StringBuilder resultStr = new StringBuilder();
        for (int i = 0; i < xStr.length(); i++) {
            int curNum = Integer.parseInt(String.valueOf(xStr.charAt(i)));
            Integer searchNum = searchMax(nums, curNum, allowMax);
            if (searchNum == null) {
                allowMax = true;
            } else {
                resultStr.append(searchNum);
                if (searchNum < curNum) {
                    allowMax = true;
                }
            }
        }

        return Integer.parseInt(resultStr.toString());
    }

    public Integer searchMax(int[] nums, int curNum, boolean allowMax) {
        if (allowMax) {
            return nums[nums.length - 1];
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == curNum) {
                return nums[i];
            }
            if (i < nums.length - 1) {
                if (nums[i] < curNum && nums[i + 1] > curNum) {
                    return nums[i];
                }
            }

        }

        return null;
    }

}
